import React, { PropTypes, Component } from 'react';
import { Link } from 'react-router';
import style from './WorkloadM.css';
import tips from './../imgs/workload_tips.png'
import {myAjaxGet, getAdminInfo, getAuthShop, myAjaxJson, ROOTURL } from './../publicAPI/publicAPI';




export default React.createClass({
	getInitialState: function() {
		let _this = this;
		
		//获取当前登录信息，用于记录订单修改人
		getAdminInfo(function(data) {
			console.log(data);
			this.setState({
				userId: data.id,
				userName: data.uname,
			});
		}.bind(_this), function(error) {})

      	//获取所有店铺名与id对应信息
		getAuthShop(null, function(data) {
			console.log(data);
			var shopsForAdm = [];
			let shopsId = {};//[id]-name
			let shopsM = {};
			data.forEach((shopMes) => {
				shopsForAdm.push(shopMes.dname);
				shopsId[shopMes.id] = shopMes.dname;
				shopsM[shopMes.dname] = shopMes.id;
			}); 
			console.log(shopsForAdm);
			this.setState({
				shopsData: data,
				shopsForAdm: shopsForAdm,
				shopsId: shopsId,
				shopsM: shopsM,
			}, this.getServantM());
		}.bind(_this));

		

	    return {
	    	shopsForAdm: [],
	    	baberArray: [],
	    	//shopsData: [],
	    	assistantArray: [],
	    	serTypesForShop: [],
	    	showTips: false,

	    	
	    	//订单状态
	        shop: '',
	        baber: '',
	        serType: '',
	        grossPay: '',
	        netPay: '',
	        payment: '',
	        assistant: '',
	        isChoosed: false,
	        tmServe: 0,
	        message: '',
	        //tmCreate: 0,
	        creator: '',
	        //tmChange: 0,
	        changer: '',
	        attachingId: '',
		};
	},

	componentWillMount: function() {
		let _this = this;
		this.searchAttaching(this.props.params.id);

	},
	componentDidMount: function() {
		//let _this = this;
	
	},

	//查询该订单是否有从订单
	searchAttaching: function(id) {
		let _this = this;
		myAjaxJson(ROOTURL +'contract/offline/search.api', 'POST', {attaching: 65634}, function(data) {
			console.log(data);
			data.map(function(searchData, idx) {
				if(searchData.attaching&&!searchData.dd) {
					//let attachingIds = [];
					_this.setState({
						attachingId: searchData.id,
					});
				}
			});
		}, function(error) {});
	},

	getServantM: function() {
		let _this = this;
		//获取所有服务人员信息
        myAjaxJson(ROOTURL +'servant/profile/search.api', 'POST', {}, function(data) {
        	console.log(data);
        	let servantsM = {};//[id]-name
        	let servantsId = {};//[name]-id
        	data.forEach(function(servant) {
          		servantsM[servant.id] = servant.meta.name;
          		servantsId[servant.meta.name] = servant.id;
        	});
        	console.log(servantsM);
        	this.setState({
        		servantsData: data,
            	servantsM: servantsM,
            	servantsId: servantsId,
        	},_this.handleGetInfo());
        	
      	}.bind(_this), function(error) {})
	},

	handleGetInfo: function() {
		let _this = this;
		//获取要修改的订单信息
		myAjaxGet(ROOTURL +'contract/offline/instance.api', {id: this.props.params.id}, function(data) {
			console.log(data);
			console.log(this.state.servantsM[data.servantId]);
			this.setState({
				shop: this.state.shopsId[data.shopId],
		        baber: this.state.servantsM[data.servantId],
		        serType: data.meta.serType,
		        grossPay: data.grossPay,
		        netPay: data.netPay,
		        payment: data.meta.payment,
		        assistant: data.meta.assistant,
		        isChoosed: data.meta.isChoosed,
		        tmServe: data.tmServe,
		        message: data.meta.message,
		        tmCreate: data.tmCreate,
		        creator: data.meta.creatorName,
		        tmChange: data.meta.tmChange||null,
		        whoChange: data.meta.whoChange||'无',
		        isChecked: data.meta.isChecked,
		        permission: data.meta.permission,
		        whoChecked: data.meta.whoChecked,
			});
		}.bind(_this), function(error) {});
	},


	/*renderBaber: function(shopSelect) {

		let baberArray = this.state.servantsData.filter(function(servantData) {
		    return !servantData.dd&&(servantData.meta.shop==shopSelect)&&(!servantData.meta.isAssistant)
		});
		//console.log(baberArray);
		return (
			baberArray.map((baberData, idx) => {
				return <option value={baberData.meta.name} key={idx} >{baberData.meta.name}</option>
			})
		);
	},

	renderAssistant: function(shopSelect) {
		let assistantArray = this.state.servantsData.filter(function(servantData) {
		    return !servantData.dd&&(servantData.meta.shop==shopSelect)&&servantData.meta.isAssistant
		});
		return (
			assistantArray.map((assistantData, idx) => {
				return <option value={assistantData.meta.name} key={idx} >{assistantData.meta.name}</option>
			})
		);
	},

	renderSerType1: function(shopSelect) {
		console.log(shopSelect);
		let _this = this;
		let shopSelectData = this.state.shopsData.filter((shop, idx) => {
        	if(shop.dname == shopSelect) {
        		return true
        	} else { return false }
        });

        myAjaxJson(ROOTURL + '/serv/shop/search.api', 'POST', {id: shopSelectData.id, name: shopSelectData.dname}, function(data) {
			console.log(data);
            let serTypesId = {};//[name]-id
            let serTypesForShop = data.filter((type, idx)=> {
                serTypesId[type.dname] = type.id;
                return !type.dd
            });
            console.log(serTypesForShop);
            this.setState({
                serTypesForShop: serTypesForShop,
                serTypesId: serTypesId,
            });
        }.bind(_this), function(error) {});

	},

	renderSerType2: function(serTypesForShop) {
		return (
			serTypesForShop.map((servType, idx) => {
				return <option value={servType.dname} key={idx} >{servType.dname}</option>
			})
		);
	},*/

	handleSubmit: function(permission) {
		let _this = this;
		let nowTime = new Date();
		//let crTime = this.state.tmServe||nowTime.setHours(this.refs.crHour.value, this.refs.crMinute.value);
		//console.log(crTime);

		//判断订单是否已复核过
		if(this.state.isChecked) {
			alert('订单已审核，无法修改');
			return
		}

		//判断数据是否为空，是否格式正确
		/*if(!parseFloat(this.refs.netPay.value)) {
			alert('价格错误，请检查格式是否正确！');
			return 
		}*/

		//发送数据至服务器
		let param = {};
		//param.creator = this.state.userid;
		//订单创建时间
        //param.tmCreate = this.state.tmCreate||nowTime.getTime();
        param.id = this.props.params.id;
		//param.dd = false;
		//param.customer = this.refs.customer.value;
		//param.servant = this.state.servantsId[this.refs.baberName.value];
        //param.shop = this.state.shopsM[this.refs.shopSelect.value];
        //param.servType= this.state.serTypesId[this.refs.serType.value];
        //标准价格
        //param.grossPay = parseFloat(this.refs.grossPay.value);
        //实际支付价格
        //param.netPay = parseFloat(this.refs.netPay.value);
        //服务开始时间
        //param.tmServe = this.state.tmServe;
        param.meta =  {
            //是否是顾客指定理发师
            isChoosed: this.state.isChoosed,
            //支付方式
            payment: this.state.payment,
            //备注
            message: this.state.message,
            //订单创建人
            creatorName: this.state.creator,
            //服务类型
            serType: this.state.serType,
            //理发师助理
            assistant: this.state.assistant,
            //记录订单最后修改人
            whoChange: this.state.whoChange,
            //记录订单最后修改时间
            tmChange: this.state.tmChange,
            //是否审核
            isChecked: true,
            //是否审核通过
		    permission: permission,
		    //审核人
		    whoChecked: this.state.userName,
        }
        //没写的项目
        //param.stPayment = 16;//支付状态
        //param.tmReserve = crTime;//预计接受服务时刻
        console.log(param);

		myAjaxJson(ROOTURL + 'contract/offline/instance.api', 'POST', param, function(data3) {
			console.log(data3);
			console.log(_this.state.attachingId);
			//从订单审核的标记
			if(_this.state.attachingId) {
				param.id = _this.state.attachingId;
				console.log(param);
				myAjaxJson(ROOTURL + 'contract/offline/instance.api', 'POST', param, function(data) {
					console.log('从订单审核成功');
					alert('审核成功');
					window.location.href = `/SalaryM/WorkloadM/${_this.props.params.id}`;
				}, function(error) {
					alert('审核失败，从订单审核失败');
				});
			} else {
				alert('审核成功');
				window.location.href = `/SalaryM/WorkloadM/${_this.props.params.id}`;
			}
	
		}, function(error3) {
			alert('审核失败，哪里出现了问题');
		});
		
	},

	/*handleKeyPress: function(e) {
	    if(e.which == 13) {
	        this.handleSubmit();
	    }
	},

	//接下来是冗余的数据双向绑定，如果react有其他办法实现请告诉我！谢谢！
	changeShop: function(e) {
		console.log(e.target.value);
		let _this = this;
	    this.setState({
			shop: e.target.value,
			serTypesForShop: [],
			showTips: true,
		});
	},
	changeBarber: function(e) {
		//console.log(e.target.value);
		this.setState({
			baber: e.target.value,
		});
	},
	changeSerType: function(e) {
		this.setState({
			serType: e.target.value,
		});
	},
	changeNetPay: function(e) {
		this.setState({
			netPay: e.target.value,
		});
	},
	changeAssistant: function(e) {
		this.setState({
			assistant: e.target.value,
		});
	},
	changePayment: function(e) {
		this.setState({
			payment: e.target.value,
		});
	},
	changeIsChoosed: function() {
		this.setState({
			isChoosed: !this.state.isChoosed,
		});
	},
	changeMes: function(e) {
		this.setState({
			message: e.target.value,
		});
	},*/

	renderButton: function(isChecked) {
		if(isChecked) {
			return (
				<p>该订单已被审核</p>
			);
		} else {
			return (
			<div>
				<button className={style['workloadM_button']} onClick={this.handleSubmit.bind(this,true)}>通过</button>
				<button className={style['workloadM_button']} onClick={this.handleSubmit.bind(this,false)}>不予通过</button>
			</div>
			);
		}
	},

	render: function() {
		let tmCreate = new Date(this.state.tmCreate);
		let tmChange = new Date(this.state.tmChange);
		let tmServe = new Date(this.state.tmServe);
		//console.log(this.state);
		//console.log(this.state.shop);
		//console.log(this.state.serType);
		return (
			<div className={style['workloadM_wrapper']}>
				<div className={style['workloadM_header']}>
					<div className={style['workloadM_create']}>
					<p>订单号：<span>{this.props.params.id}</span></p>
					<p>审核人：<span>{this.state.whoChecked}</span></p>
					</div>
					<div className={style['workloadM_create']}>
						<p>订单创建时间：
							{
								this.state.tmCreate?
							    (
									<span>
										{tmCreate.getFullYear()}年
										{tmCreate.getMonth()}月
										{tmCreate.getDate()}日-
										{tmCreate.getHours()}:
										{tmCreate.getMinutes()}
									</span>
								) : (<span>无</span>)
							}
						</p>
						<p>订单创建人：{this.state.creator}</p>
					</div>
					<div className={style['workloadM_change']}>
						<p>订单最后一次修改时间：
							{
								this.state.tmChange?
							    (
									<span>
										{tmChange.getFullYear()}年
										{tmChange.getMonth()}月
										{tmChange.getDate()}日-
										{tmChange.getHours()}:
										{tmChange.getMinutes()}
									</span>
								) : (<span>无</span>)
							}
						</p>
					<p>订单最后一次修改人：{this.state.whoChange}</p>
					</div>
				</div>

		    	<div>
					<form className={style['workloadM_form']}>
						<p>
							<label>店铺名称：</label>
							<span>{this.state.shop}</span>
				    	
				    	</p>

				    	<p>
					    	<label>理发师姓名：</label>
					    	<span>{this.state.baber}</span>
				    	
			    		</p>

						<p>
							<label>服务项目：</label>
							<span>{this.state.serType}</span>
							
						</p>

						<p>
								<label>标准价格：</label><span>{this.state.grossPay}</span>&nbsp;&nbsp;&nbsp;
								<label>实收价格：</label><span>{this.state.netPay}</span>
						</p>
						
						<p>
							<label>收款渠道：</label>
							<span>{this.state.payment}</span>
						</p>

						<p>
							<label>助理：</label>
							<span>{this.state.assistant}</span>
							
						</p>

						<p>
							<label style={{width: '200px'}}>顾客是否指定该理发师：</label>
							<input checked={this.state.isChoosed} type="checkbox" />
						</p>

						<p><label style={{width: '115px'}}>服务开始时间：</label>{tmServe.getFullYear()}年{tmServe.getMonth()}月{tmServe.getDate()}日{tmServe.getHours()}:{tmServe.getMinutes()}</p>
						<p><label>备注：{this.state.message}</label></p>
					</form>
		    	</div>
		    	
		    	<div>
		    		{this.renderButton(this.state.isChecked)}
					<Link to={`/SalaryM/WorkloadTable`}>
						<button className={style['workloadM_button']}>返回</button>
					</Link>
				</div>
    		</div>
		);
		
	}
});
    
